package com.mybatis.jpa.sqlbuilder;

import com.mybatis.jpa.sqlbuilder.query.parser.Part;
import com.mybatis.jpa.sqlbuilder.query.parser.PartTree;
import com.mybatis.jpa.utils.MappedStatementUtils;
import com.mybatis.jpa.utils.ObjectFacade;
import com.mybatis.jpa.utils.StopWatchExt;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class QuerySqlBuilder extends SqlBuilder {

    private static final Logger logger = LoggerFactory.getLogger( QuerySqlBuilder.class);
    @Override
    public String buildSql(MetaObject metaStatementHandler) throws Exception {
        StopWatchExt stopWatchExt = new StopWatchExt();
        MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
        Map<String, Object> parameterMap = super.getParamMap(metaStatementHandler);
        String method = MappedStatementUtils.getClassMethod(mappedStatement);
        Class entityClass = MappedStatementUtils.getEntityClass(mappedStatement);

        PartTree partTree = new PartTree(method, entityClass, parameterMap);
        List<Part> list = partTree.list();
        String sql = genSql(entityClass, list);
        logger.info("生成select sql耗时：{}", stopWatchExt.getTimeWithReset(true));
        return sql;
    }

    private String genSql(Class entityClass, List<Part> list) {
        ObjectFacade objectFacade = new ObjectFacade(entityClass);
        String columns = objectFacade.getColumnNames().stream().collect(Collectors.joining(","));
        String table = objectFacade.getTableName();
        String condition = list.stream().map(Part::getSqlCondition).collect(Collectors.joining());
        String sql = "select " + columns + " from " + table + " where 1 = 1 " + condition;
        return sql;
    }
}
